package apps.softtech.gplus;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.fastmarket.ActivityRegister;
import apps.softtech.fastmarket.R;
import apps.softtech.fastmarket.model.UserInfo;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.moments.ItemScope;
import com.google.android.gms.plus.model.moments.Moment;
import com.google.android.gms.plus.model.people.Person;
import com.google.android.gms.plus.model.people.Person.Name;

public class SignInGoogle extends Activity implements ConnectionCallbacks,
		OnConnectionFailedListener {

	private Context mContext;
	SignInButton btnSignIn;
	Button btnSignOut;

	private static final int RC_SIGN_IN = 0;
	private static final String TAG = null;

	private GoogleApiClient mGoogleApiClient;
	protected boolean mSignInClicked ;

	/*
	 * A flag indicating that a PendingIntent is in progress and prevents us
	 * from starting further intents.
	 */
	private boolean mIntentInProgress;
	private ConnectionResult mConnectionResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sign_in_google);
		mContext = this;
		mGoogleApiClient = new GoogleApiClient.Builder(this)
				.addConnectionCallbacks(this)
				.addOnConnectionFailedListener(this).addApi(Plus.API)
				.addScope(Plus.SCOPE_PLUS_LOGIN).build();
		btnSignIn = (SignInButton) findViewById(R.id.sign_in_button);
		btnSignIn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (v.getId() == R.id.sign_in_button
						&& !mGoogleApiClient.isConnecting()) {
					mSignInClicked = true;
					mGoogleApiClient.connect();

				}
			}
		});
		btnSignOut = (Button) findViewById(R.id.sign_out);
		btnSignOut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mGoogleApiClient.isConnected()) {
					Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
					mGoogleApiClient.disconnect();
					Toast.makeText(mContext, "signed out", Toast.LENGTH_LONG)
							.show();
				}
			}
		});

	}

	protected void onStop() {
		super.onStop();

		if (mGoogleApiClient.isConnected()) {
			mGoogleApiClient.disconnect();
		}
	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {

		if (!mIntentInProgress) {
			// Store the ConnectionResult so that we can use it later when the
			// user clicks
			// 'sign-in'.
			mConnectionResult = result;

			if (mSignInClicked) {
				// The user has already clicked 'sign-in' so we attempt to
				// resolve all
				// errors until the user is signed in, or they cancel.
				resolveSignInError();
			}
		}
	}

	private void resolveSignInError() {
		if ((mConnectionResult).hasResolution()) {
			try {
				mIntentInProgress = true;
				startIntentSenderForResult(mConnectionResult.getResolution()
						.getIntentSender(), RC_SIGN_IN, null, 0, 0, 0);
			} catch (SendIntentException e) {
				// The intent was canceled before it was sent. Return to the
				// default
				// state and attempt to connect to get an updated
				// ConnectionResult.
				mIntentInProgress = false;
				mGoogleApiClient.connect();
			}
		}
	}

	@Override
	public void onConnected(Bundle arg0) {

		// We've resolved any connection errors. mGoogleApiClient can be used to
		// access Google APIs on behalf of the user.
		mSignInClicked = false;
		// Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
		if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
			Person currentPerson = Plus.PeopleApi
					.getCurrentPerson(mGoogleApiClient);
			String personName = currentPerson.getDisplayName();
			Name name = currentPerson.getName();
			String personGooglePlusProfile = currentPerson.getUrl();
			String personPhoto = currentPerson.getImage().getUrl();
			String personGender = String.valueOf(currentPerson.getGender());
			String personBirthday = currentPerson.getBirthday();
			String personEmail = Plus.AccountApi
					.getAccountName(mGoogleApiClient);

			Toast.makeText(this, personName, Toast.LENGTH_LONG).show();

			Log.i(TAG, personName);
			Intent intent = new Intent(mContext, ActivityRegister.class);
			intent.putExtra(UserInfo.USERNAME, personName);
			intent.putExtra("avatar", personPhoto);
			intent.putExtra(UserInfo.EMAIL, personEmail);
			setResult(ActivityRegister.RESULT_GOOGLE, intent);
			this.finish();
		}

	}

	protected void onActivityResult(int requestCode, int responseCode,
			Intent intent) {
		if (requestCode == RC_SIGN_IN) {
			if (responseCode != RESULT_OK) {
				mSignInClicked = false;
			}

			mIntentInProgress = false;

			if (!mGoogleApiClient.isConnecting()) {
				mGoogleApiClient.connect();
			}
		}
	}

	@Override
	public void onConnectionSuspended(int arg0) {
		mGoogleApiClient.connect();
	}

}
